package cn.xdf.demo01;

import cn.xdf.entity.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.persistence.*;
import java.util.List;

public class Demo03_JPQL {
    //创建实体类管理器工厂对象
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("dev");//持久化单元

    //创建实体管理器
    EntityManager entityManager=entityManagerFactory.createEntityManager();

    //获取事务管理器
    EntityTransaction transaction = entityManager.getTransaction();

    @Before
    public void begin(){
        //开启事务
        transaction.begin();

    }

    @After
    public void after(){
        //提交事务
        transaction.commit();
        entityManager.close();
        entityManagerFactory.close();
    }


    @Test
    public void test01(){
        String JPQL ="select u from User u order by u.id desc";//这是实体类名
        //简写
        //String JPQL="form User";

        //创建一个查询
        Query query = entityManager.createQuery(JPQL);

        List<User> resultList = query.getResultList();//查询的获取多个结果集
        for(User user:resultList){
            System.out.println(user);
        }

    }

    @Test
    public void test02(){
        String JPQL ="from User u where u.username like ? ";//这是实体类名

        //创建一个查询
        Query query = entityManager.createQuery(JPQL);
        query.setParameter(1,"%h%");

        List<User> resultList = query.getResultList();//查询的获取一个结果集
        for(User user:resultList){
            System.out.println(user);
        }

    }

    @Test
    public void test03(){
        String JPQL ="from User  ";//这是实体类名

        //创建一个查询
        Query query = entityManager.createQuery(JPQL);
        query.setFirstResult(2);//从下标2开始查
        query.setMaxResults(3);//查询3条记录

        List<User> resultList = query.getResultList();//查询的获取一个结果集
        for(User user:resultList){
            System.out.println(user);
        }

    }

    @Test
    public void test04(){
        String JPQL ="from User u where id=?  ";//这是实体类名

        //创建一个查询
        Query query = entityManager.createQuery(JPQL);
        query.setParameter(1,5);


        User user = (User) query.getSingleResult();//返回单个结果集

        System.out.println(user);
    }


    @Test
    public void test05(){
        String JPQL ="select count(u.id) from User u  ";//这是实体类名

        //创建一个查询
        Query query = entityManager.createQuery(JPQL);


        Long count = (Long) query.getSingleResult();//返回单个结果集

        System.out.println(count);
    }




}
